import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import Navbar from './components/Navbar';
import Home from './pages/Home';
import Borrow from './pages/Borrow';
import Lend from './pages/Lend';
import Profile from './pages/Profile';
import CreditProof from './pages/CreditProof';
import Account from './pages/Account';

const theme = createTheme({
  palette: {
    mode: 'light',
    primary: {
      main: '#1976d2',
    },
    secondary: {
      main: '#dc004e',
    },
  },
});

function App() {
  const [user, setUser] = useState(null);
  const [error, setError] = useState('');

  useEffect(() => {
    // 检查本地存储中是否有用户信息
    const savedUser = localStorage.getItem('user');
    if (savedUser) {
      setUser(JSON.parse(savedUser));
    }
  }, []);

  const login = async (username, password) => {
    try {
      console.log('Attempting login with:', { username, password });
      const response = await fetch('http://localhost:3001/api/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, password }),
      });

      const data = await response.json();
      console.log('Login response:', data);
      
      if (data.success) {
        setUser(data.user);
        localStorage.setItem('user', JSON.stringify(data.user));
        setError('');
        return true;
      } else {
        setError(data.message || '登录失败');
        return false;
      }
    } catch (err) {
      console.error('Login error:', err);
      setError('登录失败，请检查网络连接');
      return false;
    }
  };

  const logout = () => {
    setUser(null);
    localStorage.removeItem('user');
  };

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Router>
        <Navbar user={user} onLogout={logout} />
        <Routes>
          <Route path="/" element={
            user ? <Navigate to="/profile" /> : <Home onLogin={login} error={error} />
          } />
          <Route path="/borrow" element={
            user ? <Borrow user={user} /> : <Navigate to="/" />
          } />
          <Route path="/lend" element={
            user ? <Lend user={user} /> : <Navigate to="/" />
          } />
          <Route path="/profile" element={
            user ? <Profile user={user} /> : <Navigate to="/" />
          } />
          <Route path="/credit-proof" element={
            user ? <CreditProof user={user} /> : <Navigate to="/" />
          } />
          <Route path="/account" element={
            user ? <Account user={user} /> : <Navigate to="/" />
          } />
        </Routes>
      </Router>
    </ThemeProvider>
  );
}

export default App; 